package com.android.plc.ui.adapter;

import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;

import com.android.plc.CONST.COMMAND;
import com.android.plc.R;
import com.android.plc.classholder.BasicItem.Type;
import com.android.plc.classholder.Unit;
import com.android.plc.provider.PLC;
import com.android.plc.util.CursorUtil;

public class DeviceAdapter extends EditorAdapter
{
	private int mDeviceStatus = 0;
	public String mEditString;
	public String mAllString;

	public DeviceAdapter(Context context, Cursor cursor, int item_id, String[] from, int[] to, boolean edit)
	{
		super(context, cursor, item_id, from, to, edit);
		Resources resources = context.getResources();
		mAllString = resources.getString(R.string.all_device);
		mEditString = resources.getString(R.string.add);
	}

	@Override
	public Uri getUri()
	{
		return PLC.Devices.CONTENT_URI;
	}

	@Override
	public String getEditString()
	{
		return mEditString;
	}

	@Override
	public String getAllString()
	{
		return mAllString;
	}

	@Override
	public Unit getItem(Type type)
	{
		return new Unit(type);
	}

	@Override
	public Unit getItem(Cursor cursor, int index)
	{
		return CursorUtil.buildUnitFromCursor(cursor, index);
	}

	public void setDeviceOn(int index, int command)
	{
		if (index >= 0 && index < 16)
		{
			int mask = 1 << index;
			boolean isOn = isDeviceOn(index);
			if (isOn && (command == COMMAND.OFF || command == COMMAND.STATUSOFF))
			{
				mDeviceStatus = mDeviceStatus - mask;
			} else if (!isOn && (command == COMMAND.ON || command == COMMAND.STATUSON))
			{
				mDeviceStatus = mDeviceStatus + mask;
			}
		}
	}

	public boolean isDeviceOn(int index)
	{
		if (index < 0 | index >= 16)
		{
			return false;
		}
		int mask = 1 << index;
		return (mDeviceStatus & mask) == mask;
	}

	public int findIndexForDevice(int home_unit)
	{
		for (int i = 0; i < getCount(); i++)
		{
			Unit item = (Unit) getItem(i);
			if (item.code == home_unit)
			{
				return coverPosition(i);
			}
		}
		return -1;
	}
}
